package cn.office.utils;

import cn.hutool.core.lang.UUID;
import cn.office.enums.file.FileContentTypeEnums;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Slf4j
public class ExcelUtils {

    /**
     * 简单的写入Excel
     * 注意 simpleWrite在数据量不大的情况下可以使用（5000以内，具体也要看实际情况），数据量大参照 重复多次写入
     *
     * @param list<T>
     * @param clazz<T>
     * @param fileName  文件名称不加后缀拓展名
     * @param excelEnum {@link FileContentTypeEnums.excelTypeEnum}
     * @param response  响应对象
     */
    public static <T> void simpleWriteExcel(List<T> list, Class<T> clazz, String fileName, FileContentTypeEnums.excelTypeEnum excelEnum, HttpServletResponse response) {
        // 创建一个输出流，存放excel文件
        ByteArrayOutputStream byteArrayOutputStream = null;
        // 创建一个输入流，写入response中
        ByteArrayInputStream byteArrayInputStream = null;
        // 创建一个输出流，接收Response的输出流
        OutputStream outputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            String traceId = UUID.fastUUID().toString(true);
            log.info("生成excel文件入参[{}]:{}", traceId, JSON.toJSONString(list));
            Instant now = Instant.now();
            // 将excel文件写入到输出流中
            EasyExcel.write(byteArrayOutputStream, clazz).sheet("sheet01").doWrite(() -> {
                // todo...
                return list;
            });
            BigDecimal fileSize = BigDecimal.valueOf(byteArrayOutputStream.size()).divide(BigDecimal.valueOf(1024), 2, BigDecimal.ROUND_HALF_UP);
            //创建inputStream流
            byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            // TODO:设置response参数
            // xlsx格式 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
            // xls格式 application/vnd.ms-excel
            response.setContentType(excelEnum.getContentType());
            response.setCharacterEncoding("utf-8");
            fileName = fileName + "." + excelEnum.getFileExtension();
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''"
                    + URLEncoder.encode(fileName, "UTF8"));
            // 拿到输出流，并写入到response中
            outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = byteArrayInputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            outputStream.flush();
            log.info("生成excel文件[{}]:文件名称:{},文件大小{}KB、耗时:{}毫秒", traceId, fileName, fileSize, ChronoUnit.MILLIS.between(now, Instant.now()));
        } catch (Exception e) {
            log.error("生成excel错误:", e);
        } finally {
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    log.error("关闭输出流异常：\n{}", e);
                }
            }
            if (byteArrayInputStream != null) {
                try {
                    byteArrayInputStream.close();
                } catch (IOException e) {
                    log.error("关闭输入流异常：\n{}", e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("关闭输出流异常：\n{}", e);
                }
            }
        }
    }

    /**
     * 简单的写入Excel
     * 注意 simpleWrite在数据量不大的情况下可以使用（5000以内，具体也要看实际情况），数据量大参照 重复多次写入
     *
     * @param list<T>
     * @param clazz<T>
     * @param fileName  文件名称不加后缀拓展名
     * @param excelEnum {@link FileContentTypeEnums.excelTypeEnum}
     * @param response  响应对象
     */
    public static <T> void complexWriteExcel(List<T> list, Class<T> clazz, String fileName, FileContentTypeEnums.excelTypeEnum excelEnum, HttpServletResponse response) {
        // 创建一个输出流，存放excel文件
        ByteArrayOutputStream byteArrayOutputStream = null;
        // 创建一个输入流，写入response中
        ByteArrayInputStream byteArrayInputStream = null;
        // 创建一个输出流，接收Response的输出流
        OutputStream outputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            String traceId = UUID.fastUUID().toString(true);
            log.info("生成excel文件入参[{}]:{}", traceId, JSON.toJSONString(list));
            Instant now = Instant.now();
            // 将excel文件写入到输出流中
            EasyExcel.write(byteArrayOutputStream, clazz).sheet("sheet01").doWrite(() -> {
                // todo...
                return list;
            });
            BigDecimal fileSize = BigDecimal.valueOf(byteArrayOutputStream.size()).divide(BigDecimal.valueOf(1024), 2, BigDecimal.ROUND_HALF_UP);
            //创建inputStream流
            byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            // TODO:设置response参数
            // xlsx格式 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
            // xls格式 application/vnd.ms-excel
            response.setContentType(excelEnum.getContentType());
            response.setCharacterEncoding("utf-8");
            fileName = fileName + "." + excelEnum.getFileExtension();
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''"
                    + URLEncoder.encode(fileName, "UTF8"));
            // 拿到输出流，并写入到response中
            outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = byteArrayInputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            outputStream.flush();
            log.info("生成excel文件[{}]:文件名称:{},文件大小{}KB、耗时:{}毫秒", traceId, fileName, fileSize, ChronoUnit.MILLIS.between(now, Instant.now()));
        } catch (Exception e) {
            log.error("生成excel错误:", e);
        } finally {
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    log.error("关闭输出流异常：\n{}", e);
                }
            }
            if (byteArrayInputStream != null) {
                try {
                    byteArrayInputStream.close();
                } catch (IOException e) {
                    log.error("关闭输入流异常：\n{}", e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("关闭输出流异常：\n{}", e);
                }
            }
        }
    }

}
